package com.cxm.qyyz.core.http;

import com.cxm.qyyz.base.mvp.BaseContract;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

public abstract class DefaultObserver<T> implements Observer<T> {

    private BaseContract.BaseView mView;
    //true的时候为页面主要逻辑，失败需要重新请求
    private boolean errType;
    private int errMode;
    private Disposable task;

    public DefaultObserver() {
        this(null, false, 0);
    }

    public DefaultObserver(BaseContract.BaseView mView) {
        this(mView, false, 0);
    }

    public DefaultObserver(BaseContract.BaseView mView, boolean errType) {
        this(mView, errType, 0);
    }

    public DefaultObserver(BaseContract.BaseView mView, int errMode) {
        this(mView, false, errMode);
    }

    public DefaultObserver(BaseContract.BaseView mView, boolean errType, int errMode) {
        this.mView = mView;
        this.errType = errType;
        this.errMode = errMode;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        task = d;
        if (errMode == 1 && mView != null) {
            mView.onLoad();
        }
    }

    @Override
    public void onNext(@NonNull T t) {
        onSuccess(t);
    }

    protected abstract void onSuccess(T data);

    @Override
    public void onError(@NonNull Throwable e) {
        dealWithTask();
        ErrorHandler.handleError(e, mView, errType);
    }

    @Override
    public void onComplete() {
        dealWithTask();
    }

    private void dealWithTask() {
        if (errMode == 1 && mView != null) {
            mView.onData();
        }
    }

    public void stopTask() {
        if (task != null && !task.isDisposed()) {
            task.dispose();
        }
    }
}
